<template>
	<page-meta>
		<navigation-bar />
	</page-meta>
	<view>
		<view class="status_bar" :style="{height: statusMenuButton+'px'}"><!-- 这里是状态栏 -->
			<view v-if="Object.keys(mainPageData).length !== 0" class="jiaonang row a-center"
				:style="{marginTop:  statusHeight+'px', height: menuButtonHeight+'px'} ">
				{{mainPageData.company.name}}
			</view>
		</view>
		<view class="search row a-center" style="height: 50px;" :style="{top:statusMenuButton+'px'}">
			<view class="ipt flex-1">
				<uni-easyinput class="test" prefixIcon="search" confirmType="search" v-model="station_name" placeholder="站点搜索" @confirm="search" @clear="search"></uni-easyinput>
			</view>
			<view class="scanCode row a-center j-center" @click="scanCode">
				<image style="width: 21px;height: 21px;" src="../../static/index/scanCode.png" mode=""></image>
			</view>
		</view>
	</view>

	<mescroll-body @init="mescrollInit" :down="downOption" @down="downCallback" @up="upCallback">
		<view :style="{marginTop: statusMenuButton+50+'px'}" style="background-color: #F6F6F6;">
			<view class="stationStatistics" v-if="Object.keys(mainPageData).length !== 0">
				<uni-section title="站点统计" titleFontSize="28rpx" titleColor="#212121">
					<template v-slot:decoration>
						<view class="decoration"></view>
					</template>
					<view class="statistics row">
						<view class="charts-box">
							<l-echart ref="chart" @finished="initChart" @touchmove.stop @touch.stop></l-echart>
							<!-- <qiun-data-charts :canvas2d="true" :canvasId="generateRandomString(10)" type="ring"
								:opts="opts" :chartData="chartData"></qiun-data-charts> -->
						</view>
						<view class="info flex-1 row flex-column j-sb">
							<view class="zongshu row a-center j-sb">
								<view class="zhongshuText">
									站点总数
								</view>
								<view class="zhandianNum">
									{{ mainPageData.station.abnormal + mainPageData.station.fire + mainPageData.station.normal + mainPageData.station.offline}}
								</view>
							</view>
							<view class="status row">
								<view class="statusItem row a-center j-center flex-1">
									正常
								</view>
								<view class="statusItem row a-center j-center flex-1">
									异常
								</view>
								<view class="statusItem row a-center j-center flex-1">
									火警
								</view>
								<view class="statusItem row a-center j-center flex-1" style="border-right: none;">
									离线
								</view>
							</view>
							<view class="statusNum row">
								<view style="color: #3665FF" class="statusNumItem row a-center j-center flex-1">
									{{mainPageData.station.normal}}
								</view>
								<view style="color: #1C1736" class="statusNumItem row a-center j-center flex-1">
									{{mainPageData.station.abnormal}}
								</view>
								<view style="color: #FE6351" class="statusNumItem row a-center j-center flex-1">
									{{mainPageData.station.fire}}
								</view>
								<view style="color: #acacac" class="statusNumItem row a-center j-center flex-1">
									{{mainPageData.station.offline}}
								</view>
							</view>
						</view>
					</view>
				</uni-section>
			</view>
			<view class="delEvent" v-if="Object.keys(mainPageData).length !== 0">
				<uni-section title="事件处理" titleFontSize="28rpx" titleColor="#212121">
					<template v-slot:decoration>
						<view class="decoration"></view>
					</template>
					<view class="eventWrap row j-sb">
						<view class="event row">
							<view class="eventIcon row flex-column a-center j-sa">
								<view class="icon">
									<image style="width: 70rpx; height: 90rpx;" src="../../static/index/alarm.png"
										mode=""></image>
								</view>
								<view class="iconText">
									告警
								</view>
							</view>
							<view class="eventInfo flex-1 row flex-column j-sb">
								<view class="infoItem row j-sb a-center">
									<view class="infoName">
										提示
									</view>
									<view class="infoNum">
										{{mainPageData.alarm.alarm_level_1}}
									</view>
								</view>
								<view class="infoItem row j-sb a-center">
									<view class="infoName">
										一般
									</view>
									<view class="infoNum">
										{{mainPageData.alarm.alarm_level_2}}
									</view>
								</view>
								<view class="infoItem row j-sb a-center">
									<view class="infoName">
										重要
									</view>
									<view class="infoNum">
										{{mainPageData.alarm.alarm_level_3}}
									</view>
								</view>
								<view class="infoItem row j-sb a-center">
									<view class="infoName">
										紧急
									</view>
									<view class="infoNum">
										{{mainPageData.alarm.alarm_level_4}}
									</view>
								</view>
							</view>
						</view>
						<view class="event row">
							<view class="eventIcon row flex-column a-center j-sa">
								<view class="icon">
									<image style="width: 100rpx; height: 84rpx;" src="../../static/index/hitch.png"
										mode=""></image>
								</view>
								<view class="iconText">
									故障
								</view>
							</view>
							<view class="eventInfo flex-1 row flex-column j-sa">
								<view class="infoItem row j-sb a-center">
									<view class="infoName">
										轻微
									</view>
									<view class="infoNum">
										{{mainPageData.breakdown.breakdown_level_1}}
									</view>
								</view>
								<view class="infoItem row j-sb a-center">
									<view class="infoName">
										一般
									</view>
									<view class="infoNum">
										{{mainPageData.breakdown.breakdown_level_2}}
									</view>
								</view>
								<view class="infoItem row j-sb a-center">
									<view class="infoName">
										严重
									</view>
									<view class="infoNum">
										{{mainPageData.breakdown.breakdown_level_3}}
									</view>
								</view>
								<view class="infoItem row j-sb a-center">
									<view class="infoName">
										重大
									</view>
									<view class="infoNum">
										{{mainPageData.breakdown.breakdown_level_4}}
									</view>
								</view>
							</view>
						</view>
					</view>
				</uni-section>
			</view>
			<view class="stationList">
				<uni-section title="站点概况" titleFontSize="28rpx" titleColor="#212121">
					<!-- <template v-slot:decoration>
						<view class="decoration"></view>
					</template> -->
					<view class="list" v-for="(item,index) in stationList" :key="index">
						<view class="parentName">
							{{item.use_company}}（{{item.station.length}}）
						</view>
						<view class="listItem" v-for="(stationItem,stationIndex) in item.station" :key="stationIndex">
							<view class="stationName row j-sb">
								<view class="">
									{{stationItem.name}}
								</view>
								<view class="ctrl row j-end" style="width: 80rpx;" @click="goCtrl(stationItem.sn, stationItem.name)">
									<image style="width: 32rpx;height: 32rpx;" src="../../static/index/ctrl.png" mode=""></image>
								</view>
							</view>
							<view class="stationInfo row j-sb" @click="goStationBoard(stationItem.id)">
								<view class="stationIcon">
									<!-- asdf -->
									<image style="width: 56px;height: 56px;" src="../../static/index/stationIcon.png"
										mode="widthFix"></image>
								</view>
								<view class="stationStatus flex-1 row a-center">
									<view class="statusItem row">
										<view class="statusName">
											通信
										</view>
										<view v-if="stationItem.link === '在线'" class="statusIcon">
											<image style="width: 11px;height: 11px;"
												src="../../static/index/statusIcon.png" mode=""></image>
										</view>
										<view v-else class="statusIcon">
											<image style="width: 11px;height: 11px;"
												src="../../static/index/statusIcon1.png" mode=""></image>
										</view>
									</view>
									<view class="statusItem row">
										<view class="statusName">
											状态
										</view>
										<view v-if="stationItem.status === '正常'" class="statusIcon">
											<image style="width: 11px;height: 11px;"
												src="../../static/index/statusIcon.png" mode=""></image>
										</view>
										<view v-else-if="stationItem.status === '离线'" class="statusIcon row a-center">
											<image style="width: 11px;height: 11px;"
												src="../../static/index/statusIcon1.png" mode=""></image>
										</view>
										<view v-else class="statusIcon row a-center">
											<image style="width: 11px;height: 11px;"
												src="../../static/index/statusIconRed.png" mode=""></image>
											<text>{{stationItem.status}}</text>
										</view>
									</view>
								</view>
							</view>
						</view>

					</view>
				</uni-section>
			</view>
		</view>
	</mescroll-body>
</template>

<script setup lang="ts">
	import { ref } from 'vue'
	import { onReady, onPageScroll, onReachBottom, onLoad, onShareAppMessage, onShareTimeline} from '@dcloudio/uni-app'
	import * as echarts from '../../utils/echarts.esm.min.js'
	// import * as echarts from '@/uni_modules/lime-echart/static/echarts.esm.min.js'
	import useMescroll from "@/uni_modules/mescroll-uni/hooks/useMescroll.js";
	import { request } from '../../utils';
	const statusHeight = ref<number>()
	const statusMenuButton = ref<number>()
	let menuButtonHeight = ref<number>()
	const station_name = ref('')
	const token  = uni.getStorageSync('token')
	menuButtonHeight.value = uni.getMenuButtonBoundingClientRect().height + 7
	onReady(async () => {
		uni.getSystemInfo({
			success: (res) => {
				statusHeight.value = res.statusBarHeight
				statusMenuButton.value = statusHeight.value + menuButtonHeight.value
			}
		})
		if(token) {
			// getMainPage()
		}
		// getServerData()
	})
	onShareAppMessage(():any => {
		// if (res.from === 'button') {// 来自页面内分享按钮
		//   console.log(res.target)
		// }
		// return {
		//   title: '中旭安全云',
		// }
	})
	// onShareTimeline(():any => {
		
	// })
	onLoad(() => {
		uni.$on('update', () => {
			getMainPage()
		})
	})
	const chart = ref()
	let chart1 : any
	const option = {
		series: [
			{
				name: '',
				type: 'pie',
				clockWise: false,
				radius: ['120%', '180%'],
				hoverAnimation: false,
				center: ['50%', '50%'],
				top: 'center',
				itemStyle: {
					normal: {
						opacity: 1,
						label: {
							show: false
						}
					}
				},
			},
			// {
			// 	name: '',
			// 	type: 'pie',
			// 	clockWise: false,
			// 	radius: ['100%', '130%'],
			// 	hoverAnimation: false,
			// 	center: ['50%', '50%'],
			// 	top: 'center',
			// 	itemStyle: {
			// 		normal: {
			// 			opacity: 0.6,
			// 			label: {
			// 				show: false
			// 			}
			// 		}
			// 	},
			// },
	
		]
	}
	const initChart = async () => {
		console.log(echarts)
		chart1 = await chart.value.init(echarts);
		chart1.setOption(option)
		getMainPage()
	}
	const page = ref(1)
	const pageSize = ref(10)
	const mainPageData = ref<any>({})
	const stationList = ref<any>({})
	const total = ref()
	const search = () => {
		page.value = 1
		getMescroll().resetUpScroll();
		getMainPage()
	}
	const getMainPage =async () => {
		const res:any = await request('/api/v1/getMainPage?permission=miniProgramHomePage', 
		{name: station_name.value,page: page.value, pageSize: pageSize.value}, 'GET')
		mainPageData.value = res.data
		if (page.value == 1) stationList.value = [];
		stationList.value = stationList.value.concat(res.data.data)
		total.value = res.data.total
		if(chart1) {
			chart1.setOption({
				series: [
					{
						data: [
							{ value: mainPageData.value.station.abnormal, itemStyle: { color: '#1C1736' } },
							{ value: mainPageData.value.station.offline, itemStyle: { color: '#acacac' } },
							{ value: mainPageData.value.station.normal, itemStyle: { color: '#3665FF' } },
							{ value: mainPageData.value.station.fire, itemStyle: { color: '#FE6351' } },
						]
					},
					// {
					// 	data: [
					// 		{ value: mainPageData.value.station.normal, itemStyle: { color: '#3665FF' } },
					// 		{ value: mainPageData.value.station.offline, itemStyle: { color: '#FE6351' } },
					// 	]
					// }
				]
			})
		}
		// let chartSeries = {
		// 	series: [
		// 		{
		// 			data: [
		// 				{ "name": "正常", "value": mainPageData.value.stationStatistics.normal, labelShow: false },
		// 				{ "name": "报警", "value": mainPageData.value.stationStatistics.warning, labelShow: false },
		// 				{ "name": "在线", "value": mainPageData.value.stationStatistics.online, labelShow: false },
		// 				{ "name": "离线", "value": mainPageData.value.stationStatistics.offline, labelShow: false },
		// 			]
		// 		}
		// 	]
		// };
		// chartData.value = chartSeries
	}
	const { mescrollInit, getMescroll } = useMescroll(onPageScroll, onReachBottom)
	const downOption = {
		auto: false //是否在初始化后,自动执行downCallback; 默认true
	}
	const dataList = ref(0)
	/* 自定义下拉刷新的回调,不使用useMescroll的downCallback */
	const downCallback =async (mescroll : any) => {
		page.value = 1
		pageSize.value = 10
		await getMainPage()
		mescroll.endSuccess();
		// setTimeout(() => {
		// 	dataList.value = 10
		// 	mescroll.endSuccess();
		// }, 2000)
	}

	/*上拉加载的回调: 其中mescroll.num:当前页 从1开始, mescroll.size:每页数据条数,默认10 */
	const upCallback = async (mescroll : any) => {
		page.value = mescroll.num
		pageSize.value = mescroll.size
		// mescroll.endBySize(10, 1);
		// mescroll.endSuccess(1);
		await getMainPage()
		mescroll.endBySize(10, total.value);
		// setTimeout(() => {
		// 	dataList.value += 20
		// 	// mescroll.endSuccess(20);
		// 	mescroll.endBySize(10, 21);
		// }, 1000)
	}
	const opts = ref({
		rotate: false,
		rotateLock: false,
		color: ["#3665FF", "#FE6351", "#6FABFC", "#1C1736"],
		enableScroll: false,
		padding: [-30, -30, -30, -30],
		legend: {
			show: false
		},
		dataLabel: true,
		title: {
			name: "",
			fontSize: 15,
			color: "#666666"
		},
		subtitle: {
			name: "",
			fontSize: 25,
			color: "#7cb5ec"
		},
		extra: {
			ring: {
				ringWidth: 0,
				activeOpacity: 0.5,
				activeRadius: 10,
				offsetAngle: 0,
				centerColor: '#E1E9F6',
				labelWidth: 15,
				border: true,
				borderWidth: 5,
				borderColor: "#E1E9F6",
				// linearType: "custom"
			}
		}
	})
	const chartData = ref({})
	const getServerData = () => {
		setTimeout(() => {
			let res = {
				series: [
					{
						data: [
							{ "name": "正常", "value": 15, labelShow: false },
							{ "name": "报警", "value": 0, labelShow: false },
							{ "name": "在线", "value": 15, labelShow: false },
							{ "name": "离线", "value": 0, labelShow: false },
						]
					}
				]
			};
			// chartData.value = res
		}, 500);
	}
	const generateRandomString = (length : number) => {
		const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		let randomString = '';

		while (randomString.length < length) {
			const randomChar = characters.charAt(Math.floor(Math.random() * characters.length));

			// 检查生成的字符是否以数字开头，如果是，则继续生成下一个字符
			if (randomString.length === 0 && /\d/.test(randomChar)) {
				continue;
			}

			randomString += randomChar;
		}

		return randomString;
	}
	const scanCode = () => {
		uni.scanCode({
			scanType: ['qrCode'],
			success: async (res) => {
				if (res.result) {
					await request('/api/v1/verifyScanResult', { sn: res.result }, 'GET')
					const data : any = await request('/api/v1/getStationDetails?permission=stationDetail', { sn: res.result }, 'GET')
					if (data.data.data.enable_status === '未投运') {
						uni.navigateTo({
							url: `/pages/enterstation/enterstation?id=${data.data.data.id}`
						})
					} else {
						uni.navigateTo({
							url: `/subpkg/stationBoard/stationBoard?id=${data.data.data.id}`
						})
					}
				}
			}
		})
	}
	const goStationBoard = (id:any) => {
		uni.navigateTo({
			url: `/subpkg/stationBoard/stationBoard?id=${id}`
		})
	}
	const goCtrl = (sn:any, name:any) => {
		uni.navigateTo({
			url: `/subpkg/control/control?sn=${sn}&name=${name}`
		})
	}
</script>

<style scoped lang="scss">
	$uni-success: #18bc37 !default;

	::v-deep .is-input-border {
		background-color: rgba(255, 255, 255, 0.39) !important;
		border: 1rpx solid #fff !important;
		border-radius: 40rpx;
	}

	::v-deep .content-clear-icon {
		padding-left: 30rpx;
	}

	::v-deep .uni-icons {
		color: #c0c4cc !important
	}

	::v-deep .uni-section {
		background-color: unset !important;
	}

	.decoration {
		width: 12rpx;
		height: 22rpx;
		margin-right: 4px;
		border-radius: 4rpx;
		background: linear-gradient(180deg, #2986F6 0%, #6FABFC 100%);
	}

	.status_bar {
		height: var(--status-bar-height);
		width: 100%;
		background: linear-gradient(269deg, #D6EFFF 0%, #DDE8FF 100%);
		position: fixed;
		overflow: hidden;
		top: 0;
		z-index: 999999;
	}

	.jiaonang {
		font-weight: bold;
		color: #212121;
		font-size: 28rpx;
		padding-left: 44rpx;
	}

	.search {
		position: fixed;
		left: 0;
		right: 0;
		// border: 1px solid #000;
		background: linear-gradient(269deg, #D6EFFF 0%, #DDE8FF 100%);
		padding: 0 44rpx;
		z-index: 999999;

		.scanCode {
			width: 80rpx;
			margin-left: 10rpx;
		}
	}

	.stationStatistics {
		height: 402rpx;
		padding: 0 20rpx;
		background: linear-gradient(269deg, #D6EFFF 0%, #DDE8FF 100%);
		box-shadow: 0px 8px 8px rgba(0, 93, 255, 0.16);
		margin-bottom: 15rpx;

		.statistics {
			height: 300rpx;
			background: rgba(255, 255, 255, 0.22);
			border: 1px solid #FFFFFF;
			box-shadow: 0px 8px 8px rgba(0, 93, 255, 0.16);
			border-radius: 20rpx;
			padding: 30rpx 24rpx;

			.charts-box {
				width: 40%;
				height: 100%;
			}

			.info {
				padding: 20rpx 0;
				color: #212121;

				.zongshu {
					font-weight: bold;
					padding: 0 24rpx;

					.zhongshuText {
						font-size: 32rpx;
					}

					.zongshuNum {
						font-size: 28rpx;
					}
				}

				.status {

					// border: 1px solid #000;
					.statusItem {
						border-right: 1px solid #212121;
						font-size: 24rpx;
					}
				}

				.statusNum {

					// border: 1px solid #000;
					.statusNumItem {
						font-size: 48rpx;
						font-weight: bold;
					}
				}
			}
		}
	}

	.delEvent {
		padding: 0 20rpx;
		margin-bottom: 10rpx;

		.eventWrap {
			.event {
				width: 48%;
				height: 248rpx;
				background: #fff;
				box-shadow: 0px 3px 6px rgba(142, 142, 142, 0.16);
				border-radius: 8rpx;
				padding: 30rpx 52rpx 30rpx 35rpx;

				.eventIcon {
					width: 40%;

					.iconText {
						font-size: 24rpx;
						color: #6FABFC;
						font-weight: bold;
					}
				}

				.eventInfo {
					margin-left: 30rpx;

					.infoItem {
						.infoName {
							color: #222224;
							font-size: 24rpx;
						}

						.infoNum {
							font-size: 28rpx;
							color: #000000;
							font-weight: bold;
						}
					}
				}
			}
		}
	}

	.stationList {
		padding: 0 20rpx 20rpx 20rpx;

		.list {
			// box-shadow: 0px 3px 6px rgba(170, 175, 175, 0.16);
			margin-bottom: 20rpx;
			.parentName {
				// border: 1px solid #000;
				font-size: 22rpx;
				color: #8E8E8E;
				margin: 0 5px 20rpx 5rpx;
				
			}

			.listItem {
				background-color: #fff;
				padding: 16rpx 28rpx;
				margin-bottom: 20rpx;
				border-radius: 16rpx;
				box-shadow: 0px 3px 6px rgba(170, 175, 175, 0.16);

				.stationName {
					border-bottom: 1px solid #E3F1F0;
					font-size: 26rpx;
					color: #707070;
					padding-bottom: 16rpx;
				}

				.stationInfo {
					margin-top: 15rpx;

					.stationIcon {
						width: 112rpx;
						height: 112rpx;
					}

					.stationStatus {
						margin-left: 60rpx;

						.statusItem {
							margin-right: 50rpx;

							.statusName {
								font-size: 25rpx;
								color: #484848;
								margin-right: 20rpx;
							}
						}
					}
				}
			}
		}
	}
</style>